package com.rockxin.cat.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.orhanobut.logger.Logger;
import com.rockxin.cat.R;
import com.rockxin.cat.activity.ActiveListActivity;
import com.rockxin.cat.activity.BidDetailsActivity;
import com.rockxin.cat.activity.IntroActivity;
import com.rockxin.cat.activity.PlatformNoticeActivity;
import com.rockxin.cat.activity.SafetyGuaranteeActivity;
import com.rockxin.cat.adapter.TargetListAdapter;
import com.rockxin.cat.base.BaseFragment;
import com.rockxin.cat.base.Constant;
import com.rockxin.cat.bean.BannerBean;
import com.rockxin.cat.bean.NoticeListBean;
import com.rockxin.cat.bean.UseBean;
import com.rockxin.cat.network.CatNetWork;
import com.rockxin.cat.network.HttpResult;
import com.rockxin.cat.utils.GlideImageLoader;
import com.rockxin.cat.utils.SPUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sunfusheng.marqueeview.MarqueeView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import rx.Subscriber;

/**
 * <b>类名称：    HomeFragment             <br/>
 * <b>类描述：                        <br/>
 * <b>创建人：    Lans               <br/>
 * <b>创建时间：  2018/3/1 13:11     <br/>
 * <b>修改人：                        <br/>
 * <b>修改时间：                      <br/>
 * <b>修改备注：                      <br/>
 *
 * @version 1.0.0 <br/>
 */
public class HomeFragment extends BaseFragment {
    @BindView(R.id.back_img)
    ImageView backImg;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.recyler_view)
    RecyclerView recylerView;

    private int pageNum = 1;

    private Banner banner;
    //公告
    private MarqueeView marqueeView;

    private Unbinder unbinder;

    private List<UseBean> mList;
    private TargetListAdapter mAdapter;
    //banner
    private List<String> imagesList = new ArrayList<>();

    private List<NoticeListBean> noticeList = new ArrayList<>();
    private List<BannerBean> bannerList = new ArrayList<>();

    @Override
    public void onStart() {
        super.onStart();
        if (marqueeView != null) {
            marqueeView.startFlipping();
        }
        if (banner != null) {
            banner.startAutoPlay();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (marqueeView != null) {
            marqueeView.stopFlipping();
        }
        if (banner != null) {
            banner.stopAutoPlay();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    public static HomeFragment newInstance() {
        Bundle args = new Bundle();
        HomeFragment fragment = new HomeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        final View mView = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, mView);

        initView();
        initRecyclerView();
        setListener();
        getData();
        return mView;
    }


    public void initView() {
        title.setText("岩鑫贷");
        backImg.setVisibility(View.GONE);
    }

    private void initRecyclerView() {
        mList = new ArrayList<>();

        mAdapter = new TargetListAdapter(R.layout.item_target_list, mList);
        mAdapter.addHeaderView(getHeaderView());
        recylerView.setAdapter(mAdapter);

        final LinearLayoutManager mLayoutManager = new LinearLayoutManager(getContext());
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recylerView.setLayoutManager(mLayoutManager);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                UseBean data = (UseBean) adapter.getItem(position);
                SPUtils spUtils = new SPUtils("Guide");
                spUtils.put(Constant.PREFERENCES.TERM, data.getRate_foramt());
                spUtils.put(Constant.PREFERENCES.RATE, data.getRepay_time());
                spUtils.put(Constant.PREFERENCES.BORROWMONEY, data.getBorrow_amount());

                Logger.d("onItemClick---position:" + position + "    id:" + data.getId());
                Intent intent = new Intent(mContext, BidDetailsActivity.class);
                intent.putExtra("targetId", data.getId());
                startActivity(intent);
            }
        });
        refreshLayout.setRefreshHeader(new ClassicsHeader(mContext));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));//设置Footer
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                mList.clear();
                getLoanlist();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum = pageNum + 1;
                getLoanlist();
            }
        });
    }

    private void setListener() {

    }

    private void getData() {
        getNotice();
        getBanner();
        getLoanlist();
    }

    private View getHeaderView() {
        View view = getLayoutInflater().inflate(R.layout.item_home_head, (ViewGroup) recylerView.getParent(), false);
        banner = (Banner) view.findViewById(R.id.banner);
        marqueeView = (MarqueeView) view.findViewById(R.id.marqueeView);
        ((RelativeLayout) view.findViewById(R.id.rl_one)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Logger.d("rl_one");
                startEvent(PlatformNoticeActivity.class);
            }
        });
        ((RelativeLayout) view.findViewById(R.id.rl_two)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Logger.d("rl_two");
                startEvent(IntroActivity.class);
            }
        });
        ((RelativeLayout) view.findViewById(R.id.rl_three)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Logger.d("rl_three");
                startEvent(SafetyGuaranteeActivity.class);
            }
        });
        ((RelativeLayout) view.findViewById(R.id.rl_four)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Logger.d("rl_four");
                startEvent(PlatformNoticeActivity.class);
            }
        });
        ((TextView) view.findViewById(R.id.tv_seemore)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Logger.d("hot_more");
                EventBus.getDefault().post("start", "home_money");
            }
        });
        return view;
    }


    public void getNotice() {
        final CatNetWork catNetWork = new CatNetWork();
        catNetWork.noticeList(new Subscriber<HttpResult<List<NoticeListBean>>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(HttpResult<List<NoticeListBean>> listHttpResult) {
                Logger.json(new Gson().toJson(listHttpResult));
                noticeList.addAll(listHttpResult.getData());
                initNotice();
            }
        });
    }

    public void getBanner() {
        final CatNetWork catNetWork = new CatNetWork();
        catNetWork.bannerList(new Subscriber<HttpResult<List<BannerBean>>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(HttpResult<List<BannerBean>> listHttpResult) {
                Logger.json(new Gson().toJson(listHttpResult));
                bannerList.addAll(listHttpResult.getData());
                initBanner();
            }
        });
    }

    private void initNotice() {
        List<String> info = new ArrayList<>();

        for (int i = 0, count = noticeList.size(); i < count; i++) {
            info.add(noticeList.get(i).getTitle());
        }

        marqueeView.startWithList(info);
        marqueeView.setOnItemClickListener(new MarqueeView.OnItemClickListener() {
            @Override
            public void onItemClick(int position, TextView textView) {
                Logger.d("position:" + position + "     " + textView.getText());
                Logger.d("position======:" + noticeList.get(position).getUrl());
            }
        });
    }

    private void initBanner() {
        Logger.d("initBanner------banner:");

        for (int i = 0, count = bannerList.size(); i < count; i++) {
            imagesList.add(bannerList.get(i).getCode());
        }
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(imagesList);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        banner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                Logger.d("initBanner------position:" + position);
            }
        });
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    private void getLoanlist() {
        final CatNetWork catNetWork = new CatNetWork();
        catNetWork.loanlist(String.valueOf(pageNum), "", "", "", "", "", "", new Subscriber<HttpResult<List<UseBean>>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                if (pageNum == 1) {
                    refreshLayout.finishRefresh();//传入false表示刷新失败
                } else {
                    refreshLayout.finishLoadMore();//传入false表示刷新失败
                }
            }

            @Override
            public void onNext(HttpResult<List<UseBean>> listHttpResult) {
                Logger.json(new Gson().toJson(listHttpResult));
                mList.addAll(listHttpResult.getData());
                mAdapter.notifyDataSetChanged();
                if (pageNum == 1) {
                    refreshLayout.finishRefresh();//传入false表示刷新失败
                } else {
                    refreshLayout.finishLoadMore();//传入false表示刷新失败
                }
            }
        });
    }

    private void startEvent(Class cls) {
        Intent intent = new Intent(mContext, cls);
        startActivity(intent);
    }
}
